<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="head-container-left">
        <h1>总商品列表</h1>
        <el-table ref="table"
                  stripe
                  border
                  v-loading="crud.loading"
                  height="700"
                  :row-class-name="crud.tableRowClassName"
                  :data="goodsList"
                  size="small" style="width: 100%;"
                  :show-summary="true"
                  sortable="custom"
                  @sort-change="crud.sortChange"
                  @selection-change="crud.selectionChangeHandler"
                  @row-dblclick="crud.dbClick">
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="总数量" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remainGoodsCount')" prop="remainGoodsCount" label="剩余数量" />
        </el-table>
      </div>
      <div class="head-container-right">
        <h1>
          <el-button
            class="filter-item"
            size="mini"
            @click="handleReturnSplit()"
          >
            保存拆分
          </el-button>
        </h1>
        <el-table ref="table1"  border  v-loading="crud.loading" height="340" :row-class-name="crud.tableRowClassName"
                  :data="customerList"
                  size="small" style="width: 100%;"
                  :show-summary="true"
                  sortable="custom"
                  highlight-current-row
                  @row-click="selectRow">
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName" label="客户名称" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode" label="客户编码" />
          <el-table-column :render-header="crud.renderHeader"  prop="sCustomerName" label="所属二批" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerAreaName')" prop="customerAreaName" label="区域" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerTypeName')" prop="customerTypeName" label="分类" />
<!--          <el-table-column :render-header="crud.renderHeader"  label="操作" fixed="right" width="150px" align="center">-->
<!--            <template slot-scope="scope">-->
<!--            <el-button-->
<!--              type="primary"-->
<!--              icon="el-icon-plus"-->
<!--              circle-->
<!--              :disabled="crud.order.orderStatus==='PASS'"-->
<!--              @click="crud.addRow(scope.$index)"></el-button>-->
<!--              &lt;!&ndash;              v-if="crud.data.length!==1"&ndash;&gt;-->
<!--              <el-button-->
<!--                slot="reference" class="el-icon-delete opration_icon_btn"-->
<!--                :disabled="crud.order.orderStatus==='PASS'"-->
<!--                style="border: none;width: auto;height: auto"-->
<!--                @click="delAddRow(scope.$index)"></el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
        <el-table ref="table2"  stripe border  v-loading="crud.loading" height="345" :row-class-name="crud.tableRowClassName"
                  :data="customerGoodsList"
                  size="small" style="width: 100%;"
                  :show-summary="true"
                  sortable="custom"
                >
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />
          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" >
            <template slot-scope="scope">
              <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"
                        @change="changeNum"
                        maxlength="12"  v-model="scope.row.goodsCount"
                        placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
<!--          <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remainGoodsCount')" prop="remainGoodsCount" label="辅数量" >-->
<!--            <template slot-scope="scope">-->
<!--              <el-input oninput="value=value.replace(/[^\d^\.]/g,'')"-->
<!--                        maxlength="12" v-model="scope.row.remainGoodsCount"-->
<!--                        @change="chageIndex(scope.row.remainGoodsCount,)"-->
<!--                        placeholder="请输入内容"></el-input>-->
<!--            </template>-->
<!--          </el-table-column>-->


<!--          <el-table-column :render-header="crud.renderHeader"  label="操作" fixed="right" width="150px" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button-->
<!--                type="primary"-->
<!--                icon="el-icon-plus"-->
<!--                circle-->
<!--                :disabled="crud.order.orderStatus==='PASS'"-->
<!--                @click="crud.addRow(scope.$index)"></el-button>-->
<!--              <el-button-->
<!--                slot="reference" class="el-icon-delete opration_icon_btn"-->
<!--                :disabled="crud.order.orderStatus==='PASS'"-->
<!--                style="border: none;width: auto;height: auto"-->
<!--                @click="delAddRow(scope.$index)"></el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import crudLogisticsLoad, { getReturnBottleBoxCollectSplitInfo } from '@/api/erp/logisticsLoad'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import { getCompany } from '@/api/system/company'
import {Notification} from "element-ui";
import addBatch from '@/components/addBatch/addBatch'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
// crud交由presenter持有
const defaultCrud = CRUD({ title: '采购单明细',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false,
    pass: true,
    reject: true,
    recover: true,
    invalid: true,
    print: true,
    printDetail: true
  },
  params() {
    const href = location.href.split('/')
    console.log('logisticsLoad',href)
    return {
      id: href[href.length - 1] == 'add' ? 0 : href[5], page: 0, size: 999,
    }
  },
  url: '',name:'logisticsLoadDetailSplit', sort:'t.seq,asc', crudMethod: { ...crudLogisticsLoad }})
const defaultForm = { id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null }
export default {
  name: 'crudLogisticsLoadDetailSplit',
  components: { pagination, crudOperation, rrOperation, udOperation,jtgSelectPlus,addBatch,jPrintConfig},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  dicts: ['t_buy_order_source_type','t_bas_customer_is_contact','common_yes_or_no','t_buy_order_type','common_order_status','t_buy_order_buy_channel','common_cancel_status','t_bas_goods_package_type'],

  data() {
    return {
      id: null,
      detailList:[],
      permission: {
        add: ['admin', 'logisticsLoadDetailSplit:add'],
        edit: ['admin', 'logisticsLoadDetailSplit:edit'],
        del: ['admin', 'logisticsLoadDetailSplit:del'],
        import: ['admin', 'logisticsLoadDetailSplit:import'],
        export: ['admin', 'logisticsLoadDetailSplit:export'],
        copy: ['admin', 'logisticsLoadDetailSplit:copy'],
        upload: ['admin', 'logisticsLoadDetailSplit:upload'],
        download: ['admin', 'logisticsLoadDetailSplit:download'],
      },
      rules: {
        deptId: [
          { required: true, message: '采购部门不能为空', trigger: 'blur' }
        ],
        acceptDate: [
          { required: true, message: '到货日期不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '采购单类型不能为空', trigger: 'blur' }
        ],
        buyChannel: [
          { required: true, message: '渠道类型不能为空', trigger: 'blur' }
        ],
        // sourceType: [
        //   { required: true, message: '来源类型不能为空', trigger: 'blur' }
        // ],
        customerId: [
          { required: true, message: '客户不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '业务员不能为空', trigger: 'blur' }
        ],
        isAppend: [
          { required: true, message: '是否追加不能为空', trigger: 'blur' }
        ],
        isContact: [
          { required: true, message: '是否第三方采购不能为空', trigger: 'blur' }
        ],
      },
      addRowData:{
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      },
      showAddBatchDialog: false,
      productList:[],
      goodsList: [],
      customerList: [],
      customerGoodsList: [],
    }
  },
  watch: {
  },
  created(){
    this.getInfoList()
  },
  methods: {
    getInfoList(){
      const href = location.href.split('/')
      crudLogisticsLoad.getReturnBottleBoxCollectSplitInfo({id:href[5]}).then(res => {
        console.log('href', res)
        this.goodsList = res.data.goodsList
        this.detailList = res.data.detailList
        this.detailList.forEach(item=>{
          if (item.sCustomerList.length){
            item.sCustomerName = item.sCustomerList[0].scustomerName
            item.sCustomerId = item.sCustomerList[0].scustomerId
          }
        })
        let list = res.data.detailList
        list.map((res)=>{
          this.customerList.push(res)
        })
        this.customerGoodsList =  this.customerList[0].goodsList
        this.$refs.table1.setCurrentRow(this.customerList[0])
        console.log('customergoodsList',this.customerGoodsList)
      })
    },
    selectRow(row){
      this.customerGoodsList = row.goodsList
      console.log('selectRow',row)
    },
    handleReturnSplit(res){
      const href = location.href.split('/')
      let params = {
        detailList:this.customerList,
        id: href[5]
      }
      crudLogisticsLoad.splitReturnBottleBoxCollect(params).then(res => {
        // this.getInfoList()
        if (res.status === 200){
          this.$message.success("保存成功")
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.back()
        }else {
          this.$message.error(res.msg)
        }

      })
    },
    changeNum(){
      for(let i in this.goodsList){
        let goodsCount = Number(this.goodsList[i].goodsCount)
        for(let cl in this.customerList){
          console.log(this.customerList[cl].goodsList.find(item=>item.goodsId === this.goodsList[i].goodsId).goodsCount)
          goodsCount -= Number(this.customerList[cl].goodsList.find(item=>item.goodsId === this.goodsList[i].goodsId).goodsCount)
        }
        this.$set(this.goodsList[i],'remainGoodsCount',goodsCount)
      }
    },
    afterChangeGoods(goods) {
      this.showAddBatchDialog = false
      //去重，已经去重
      let arr = this.crud.data.map(detail=>detail.goodsId)
      let _goods = []
      let result = []
      goods.forEach(good => {
        // if(!arr.includes(goods.goodsId)){
        good.isSelected = true
        this.crud.data.push(good)
        // }
      })
      // this.calcuForm()
    },
    toAddList() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //校验通过
          this.showAddBatchDialog = true
        } else {
          if (!this.crud.order.customerId) {
            this.$message.error("请先选择客户")
          }
          if (!this.crud.order.type) {
            this.$message.error("请先选择销售单类型")
          }
          // if (!this.crud.order.buyChannel) {
          //   this.$message.error("请先选择采购渠道")
          // }
        }
      })
    },
    getInfo(e){
      this.crud.order.warehouseId = e.warehouseId
      this.crud.order.contactName = e.contactName
      this.crud.order.contactPhone = e.contactPhone
      this.crud.order.deliveryAddress = e.deliveryAddress
      this.crud.order.address = e.address
      this.crud.order.deptId = e.deptId
      this.crud.order.userId = e.userId
    },
    delAddRow(i){
      if(this.$route.params.id !== 'add'){
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.delRow(i)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }else{
        this.crud.delRow(i)
      }
    },
    getValue(e,i){
      console.log('this.crud.data',this.crud.data )
      this.crud.data[i].productName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if(item.existBox === null){
          item.existBox = 0
        }
        if(item.occupyBox === null){
          item.occupyBox = 0
        }
      })
    },
    getInput(e,name,i){
      console.log(',data.goodsName',e,name,i)
      if(this.crud.data){
        if(e){
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= e
        }else{
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= null
        }
      }
    },
    // 保存
    submit(){
      var oDate1 = new Date(this.crud.order.startDate);
      var oDate2 = new Date(this.crud.order.endDate);
      if(oDate1.getTime() > oDate2.getTime()){
        this.$message({
          message: '开始日期不能大于结束日期',
          type: 'warning'
        })
        this.crud.order.startDate = null
        this.crud.order.endDate = null
        return false
      }
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        const table_rules = [
          // {name: '数量', value: 'goodsCount'},
          {name: '采购价', value: 'taxPrice'},
          // {name: '未税单价', value: 'noTaxPrice'},
          {name: '含税金额', value: 'taxAmount'},
          // {name: '未税金额', value: 'noTaxAmount'}
        ]
        const result = table_rules.some(({name, value}) => {
          const rules = this.$refs.table.data.some((item, index) => {
            if (!this.tableRules((index + 1), name, item[value])) return true
          })
          if (rules) return true
        })
        if (!result) this.save()
      })
    },
    tableRules(index, name, value) {
      if (!value) {
        Notification.error({title: '序号【' + index + '】' + name + '不能为空'})
        return false
      } else return true
    },
    getTime(date = new Date()){
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? ('0' + m) : m;
      var d = date.getDate();
      d = d < 10 ? ('0' + d) : d;
      var h = date.getHours();
      h=h < 10 ? ('0' + h) : h;
      var minute = date.getMinutes();
      minute = minute < 10 ? ('0' + minute) : minute;
      var second=date.getSeconds();
      second=second < 10 ? ('0' + second) : second;
      // +' '+h+':'+minute+':'+second;
      return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second
    },
    //保存
    save() {
      let that = this
      that.crud.loadingOpen()
      this.crud.order.detailList  = this.crud.data
      let params = this.crud.order
      crudLogisticsLoad.add(params).then(res => {
        if(res.success){
          this.crud.order  = res.data
          // this.crud.data = res.data.detailList
          let id=res.data.id
          if(this.$route.params.id == 'add'){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({params: {id}})
            this.crud.cleanItemInfo('wareReturnBottleBoxDetail_add')
          }
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          that.crud.loadingClose()
        }else{
          that.crud.loadingClose()
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        }

      }).catch((res)=>{
        that.crud.loadingClose()
      })
    },
    // 新增
    toAdd(){

      if(!this.crud.order.customerId){
        this.$message({
          message: '请先选择客户',
          type: 'error'
        })
        return false
      }
      if(!this.crud.order.type){
        this.$message({
          message: '请先选择采购单类型',
          type: 'error'
        })
        return false
      }
      // if(!this.crud.order.buyChannel){
      //   this.$message({
      //     message: '请先选择采购渠道',
      //     type: 'error'
      //   })
      //   return false
      // }
      this.crud.data.push({
        isSelected: true,id: null, orderId: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, firstUnitId: null, firstUnitCode: null, firstUnitName: null, firstUnitCount: null, effectGoodsCount: null, cutOffGoodsCount: null, taxPrice: null, noTaxPrice: null, taxBoxPrice: null, noTaxBoxPrice: null, seq: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null
      })
    },
    //修改
    toDetail(){
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },

  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.head-container{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.head-container-left{
  width: 33%;
  display: inline-block;
}
.head-container-right{
  width: 65%;
  display: inline-block;
}
</style>

